<template>
  <div class="main">
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-tickets"></i> 客户端『{{clientId}}』站点信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button type="primary" icon="el-icon-d-arrow-left" class="handle-del mr10" @click="goBack">返 回</el-button>
        <el-button type="primary" icon="el-icon-refresh" class="handle-del mr10" @click="refreshData">刷 新</el-button>
        <el-button type="primary" @click="handleSiteAdd" icon="el-icon-news">创建站点</el-button>
      </div>
      <el-table :data="tableData"
                style="width: 100%"
                ref="webSiteInfoTable"
                border
                stripe
                fit>
        <el-table-column type="index" width="55"></el-table-column>
        <el-table-column prop="siteInfo.id" label="站点ID" width="80">
        </el-table-column>
        <el-table-column prop="siteInfo.siteName" label="站点名称" width="200">
        </el-table-column>
        <el-table-column prop="siteInfo.status" label="状态" width="60" :formatter="statusFmt">
        </el-table-column>
        <el-table-column prop="siteInfo.autoStart" label="自启" width="50" :formatter="booleanFmt">
        </el-table-column>
        <el-table-column prop="siteInfo.physicalPath" label="路径">
        </el-table-column>

        <el-table-column label="操作" width="160">
          <template slot-scope="scope">
            <!--<el-button type="primary" @click="handleEdit(scope)">编辑</el-button>-->
            <el-dropdown split-button type="primary" @click="handleEdit(scope)" @command="handleCommand">
              编辑
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{cmd:0,data:scope.row}">启动</el-dropdown-item>
                <el-dropdown-item :command="{cmd:1,data:scope.row}">停止</el-dropdown-item>
                <el-dropdown-item :command="{cmd:3,data:scope.row}">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!--查看弹出框-->
    <el-dialog :title="dialogTitle" :visible.sync="editVisible">
      <el-form :model="form">
        <el-tabs type="border-card" value="baseSetting">
          <input type="hidden" v-model="form.siteInfo.id" ref="siteId" />
          <el-tab-pane label="基本设置" name="baseSetting">
            <el-form-item label="站点名称" :label-width="formLabelWidth">
              <el-input v-model="form.siteInfo.siteName" @blur="emptyCheck" required style="width:200px" placeholder="请输入站点名称" name="siteName"></el-input>
            </el-form-item>
            <el-form-item label="程序目录" :label-width="formLabelWidth">
              <el-input v-model="form.siteInfo.physicalPath" @blur="emptyCheck" required placeholder="请指定站点存放目录,必须保证盘符存在" name="sitePath"></el-input>
            </el-form-item>
            <el-form-item label="自动启动" :label-width="formLabelWidth">
              <el-switch v-model="form.siteInfo.autoStart"
                         active-color="#13ce66"
                         inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="绑定信息" name="bindings">
            <el-form-item label="主机名称(可为空)" :label-width="formLabelWidth">
              <el-input v-model="form.siteInfo.bindings[0].host" style="width:300px" placeholder="主机名称" ref="siteName"></el-input>
            </el-form-item>
            <el-form-item label="IP地址" :label-width="formLabelWidth">
              <el-input v-model="form.siteInfo.bindings[0].ipAddress" required style="width:300px" placeholder="默认输入'*'即可"></el-input>
            </el-form-item>
            <el-form-item label="端口号" :label-width="formLabelWidth">
              <el-input-number size="medium" v-model="form.siteInfo.bindings[0].port"></el-input-number>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="限额" name="limit">
            <el-form-item label="连接超时(秒)" label-width="200px">
              <el-input-number v-model="form.siteInfo.limits.connectionTimeout" controls-position="right" :min="1" :max="4294967295" class="numInputW"></el-input-number>
            </el-form-item>
            <el-form-item label="最大URL段数" label-width="200px">
              <el-input-number v-model="form.siteInfo.limits.maxUrlSegments" controls-position="right" :min="1" :max="4294967295" class="numInputW"></el-input-number>
            </el-form-item>
            <el-form-item label="最大带宽(字节/秒)" label-width="200px">
              <el-input-number v-model="form.siteInfo.limits.maxBandwidth" controls-position="right" :min="1" :max="4294967295" class="numInputW"></el-input-number>
            </el-form-item>
            <el-form-item label="最大并发连接数" label-width="200px">
              <el-input-number v-model="form.siteInfo.limits.maxConnections" controls-position="right" :min="1" :max="4294967295" class="numInputW"></el-input-number>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="程序池" name="appPool">
            <el-switch v-model="bNewAppPool"
                       :disabled="!isAddSite"
                       active-color="#13ce66"
                       inactive-color="#ff4949"
                       active-text="自动创建程序池"
                       inactive-text="使用选择程序池">
            </el-switch>
            <el-select v-model="form.siteInfo.appPoolName" :disabled="bNewAppPool" placeholder="请选择">
              <el-option v-for="item in appPools"
                         :key="item"
                         :label="item"
                         :value="item">
              </el-option>
            </el-select>
            <el-button @click="getAppPools" class="mr-5">刷新程序池</el-button>
          </el-tab-pane>
          <el-tab-pane label="站点安装包" name="installPack">
            <el-upload class="upload-demo"
                       ref="upload"
                       action="/api/FileManager/UploadFile"
                       :multiple="false"
                       :auto-upload="false"
                       :on-success="uploadSuccess"
                       :on-error="uploadError"
                       :data="siteVersionFile"
                       accept="application/zip">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
              <div class="el-upload__tip" slot="tip">只能上传zip格式站点压缩文件</div>

            </el-upload>
            <el-form-item label="决定站点版本文件的文件名" label-width="180px">
              <el-input v-model="form.siteInfoExtend.webAssemblyFileName" required style="width:300px" placeholder="输入文件全名，并存在于上传的zip包中"></el-input>
            </el-form-item>
            <el-form-item label="当前站点程序版本" label-width="180px">
              <el-input v-model="form.siteInfoExtend.webVersion" :disabled="true" style="width:300px" placeholder="文件版本号，上传后自动获取"></el-input>
            </el-form-item>
            <el-form-item label="站点程序包MD5值" label-width="180px">
              <el-input v-model="form.siteInfoExtend.webPackMd5" :disabled="true" style="width:300px" placeholder="文件MD5值，上传后自动获取"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="站点安装设置" name="installSetup">
            <el-form-item label="创建站点前执行命令" label-width="180px">
              <el-input v-model="form.siteInfoExtend.beforExecCommands" type="textarea"
                        :rows="4" placeholder="输入要执行命令，每行一个命令;例如:del /F /Q c:\tmp\*.log"></el-input>
            </el-form-item>
            <el-form-item label="创建站点后执行命令" label-width="180px">
              <el-input v-model="form.siteInfoExtend.afterExecCommands" type="textarea"
                        :rows="4" placeholder="输入要执行命令，每行一个命令;例如:del /F /Q c:\tmp\*.log"></el-input>
            </el-form-item>
            <el-form-item label="测试指令" label-width="180px">
              <el-input v-model="form.siteInfoExtend.testAction" placeholder="输入Http Get测试方法(返回内容编码只能是utf8,否则可能乱码)，只允许一个;例如: /api/TestFun?id=123456"></el-input>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">关 闭 <i class="el-icon-circle-close-outline el-icon--right"></i></el-button>
        <el-button type="primary" @click="saveEdit">提 交<i class="el-icon-edit el-icon--right"></i></el-button>
      </span>
    </el-dialog>
  </div>


</template>
<script>
  isNullOrEmpty(obj) {
    return (obj == null || obj == undefined);
  }
  export default {
    data() {
      return {
        requestId: "",
        editVisible: false,
        bNewAppPool: false,
        tableData: [],
        appPools: [],
        clientId: "",
        sessionId: "",
        appPoolQueryId: "",
        dialogTitle: "创建站点",
        formLabelWidth: "120px",
        form: {
          siteInfoExtend: {
            siteId: "",
            webPacketUrl: "",
            webPackMd5: "",
            webAssemblyFileName: "",
            webVersion: "",
            beforExecCommands: "",
            afterExecCommands: "",
            testAction: "",
          },
          siteInfo: {
            id: 0,
            siteName: "",
            autoStart: true,
            physicalPath: "D:\\CmtsWeb\\",
            status: 0,
            appPoolName: ".NET v2.0",
            bindings: [{
              host: "",
              ipAddress: "*",
              port: "8100",
              protocol: "http"
            }],
            limits: {
              connectionTimeout: 120,
              maxBandwidth: 4294967295,
              maxConnections: 4294967295,
              maxUrlSegments: 32
            },
          }
        }

      }
    },
    methods: {
      getData() {
        let url = "/api/WebSiteInfo/result?id=" + this.requestId;
        this.$axios.get(url).then((res) => {
          var body = res.data;
          console.log("请求成功");
          console.log(body);
          if (body.resultCode == 0) {
            if (body.resultCode != 0) {
              this.$message.error("查询失败:" + body.resultMsg);
              this.tableData = [];
            } else {

              this.tableData = body.data.receiveData;
              if (this.tableData == null || this.tableData == undefined || this.tableData.length < 1) {
                this.$message("会话过期，请刷新");
              }
              this.clientId = body.data.clientId;
              this.sessionId = body.data.sessionId;
              this.getAppPools(this);
            }

          } else {
            this.tableData = [];
          }
        })
          .catch(function (error) {
            console.log(error);
            //this.$message.error("查询失败");
          });
      },
      /*刷新数据*/
      refreshData() {
        let url = "/api/WebSiteInfo/query?id=" + this.sessionId;
        this.$axios.get(url)
          .then((res) => {
            var body = res.data;
            //console.log(res);
            if (body && body.resultCode == 0) {
              this.requestId = body.data;
              this.getData();
            }
          })
      },
      /*查询程序池*/
      getAppPools(parent) {
        if (!parent.sessionId) {
          console.warn("sessionId is empty");
          return;
        }
        var queryUrl = "/api/AppPool/query?id=" + parent.sessionId;
        this.$axios.get(queryUrl)
          .then((res) => {
            if (res.data.resultCode == 0) {
              var ret = res.data.data;
              parent.appPools = ret.receiveData;
            }
          });

      },

      handleSiteAdd() {
        this.editVisible = true;
        this.dialogTitle = "创建站点";
        this.bNewAppPool = true;
        this.form = {
          siteInfoExtend: {
            siteId: -1,
            webPacketUrl: "",
            webPackMd5: "",
            webAssemblyFileName: "",
            webVersion: "",
            beforExecCommands: "",
            afterExecCommands: "",
            testAction: "",
          },
          siteInfo: {
            id: -1,
            siteName: "",
            autoStart: true,
            physicalPath: "D:\\CmtsWeb\\",
            status: 0,
            appPoolName: ".NET v2.0",
            bindings: [{
              host: "",
              ipAddress: "*",
              port: "8100",
              protocol: "http"
            }],
            limits: {
              connectionTimeout: 120,
              maxBandwidth: 4294967295,
              maxConnections: 4294967295,
              maxUrlSegments: 32
            },
          }
        };
      },
      handleEdit(scope) {
        this.bNewAppPool = false;
        let item = scope.row;
        console.log(item);
        this.form.siteInfo = item.siteInfo;
        this.form.siteInfoExtend = (item.siteInfoExtend == null || item.siteInfoExtend == undefined)
          ? {
            siteId: "",
            webPacketUrl: "",
            webPackMd5: "",
            webAssemblyFileName: "",
            webVersion: "",
            beforExecCommands: "",
            afterExecCommands: "",
            testAction: "",
          } : item.siteInfoExtend;
        this.dialogTitle = "修改站点";
        this.editVisible = true;
      },
      submitUpload() {
        let upload = this.$refs.upload;

        if (!upload.uploadFiles || upload.uploadFiles.length < 1) {
          this.$message.error("请先选择上传文件");
          return;
        }
        if (this.form.siteInfoExtend.webAssemblyFileName && this.form.siteInfoExtend.webAssemblyFileName != "") {
          var name = upload.data;
          console.log(upload);
          console.log(name);
          upload.submit();
        } else {
          this.$message.error("请输入站点版本文件名称");
        }
      },
      uploadSuccess(response, file, fileList) {
        console.log(response);
        if (response.resultCode == 0) {
          this.$message("上传成功");
          this.form.siteInfoExtend.siteId = response.siteId;
          this.form.siteInfoExtend.webPacketUrl = response.webPacketUrl;
          this.form.siteInfoExtend.webPackMd5 = response.webPackMd5;
          this.form.siteInfoExtend.webVersion = response.webVersion;
        } else {
          this.$message.error("上传失败,原因:" + response.resultMsg);
          this.$alert("原因:" + response.resultMsg, "上传失败")
          this.form.siteInfoExtend.webPacketUrl = "";
          this.form.siteInfoExtend.webPackMd5 = "";
          this.form.siteInfoExtend.webVersion = "";
          this.form.siteInfoExtend.webAssemblyFileName = "";
          this.$refs.upload.clearFiles();
        }
      },
      uploadError(err, file, fileList) {
        this.$message.error("上传文件发生错误");
        this.form.siteInfoExtend.webPacketUrl = "";
        this.form.siteInfoExtend.webPackMd5 = "";
        this.form.siteInfoExtend.webVersion = "";
        this.form.siteInfoExtend.webAssemblyFileName = "";
        this.$refs.upload.clearFiles();
        console.error(err);
      },
      saveEdit() {
        if (this.form.siteInfo.siteName == "") {
          this.message.error("站点名称不能为空");
          return;
        }
        if (this.form.siteInfo.port == "") {
          this.message.error("端口号不能为空");
          return;
        }
        if (this.form.siteInfo.physicalPath == "") {
          this.message.error("路径不能为空");
          return;
        }
        if (this.bNewAppPool) {
          this.form.siteInfo.appPoolName = this.form.siteInfo.siteName;
        }
        let data = {
          "siteInfo": this.form.siteInfo,
          "siteInfoExtend": this.form.siteInfoExtend
        };
        console.log(data);

        if (this.dialogTitle == "创建站点") {
          let url = "/api/WebSiteInfo/create/" + this.sessionId;
          this.$axios.post(url, data)
            .then((res) => {
              console.log(res);
              let data = res.data;
              if (data.resultCode == 0) {
                let json = data.data.receiveData;
                if (json.resultCode == 0) {
                  this.$message("创建成功");
                  let resultTemplate = `<strong>创建结果:</strong>${json.resultMsg}<i></i> </br>
<strong>站点ID:</strong><i>${json.webSiteId}</i> </br>
<strong>接口测试结果:</strong><i>${json.testAtionResult}</i> </br>
<strong>执行命令结果:</strong><i> ${json.cmdResult}</i> </br>`
                  this.$alert(resultTemplate, {
                    dangerouslyUseHTMLString: true,
                    confirmButtonText: '确定',
                    callback: action => {
                      this.editVisible = false;
                      this.refreshData();
                    }
                  });
                } else {
                  this.$message("创建失败，原因：" + json.resultMsg);
                  this.$alert("原因:" + json.resultMsg, "创建失败")
                }
              }
            }).catch((err) => {
              console.log(err);
            });
        } else {
          let url = "/api/WebSiteInfo/modify";
          this.$axios.post(url, {

          }).then((res) => {

          }).catch((err) => {
            console.log(err);
          });
        }
      },
      goBack() {
        window.history.length > 1
          ? this.$router.go(-1)
          : this.$router.push('/')
      },
      statusFmt(row, column, cellValue, index) {

        let str = "未知";
        switch (cellValue) {
          case 0:
            str = "启动中";
            break;
          case 1:
            str = "已启动";
            break;
          case 2:
            str = "停止中";
            break;
          case 3:
            str = "已停止";
            break;
          case 4:
            str = "未知";
            break;
          default:
        }
        return str;

      },
      booleanFmt(row, column, cellValue, index) {
        return cellValue ? "是" : "否";
      },
      handleCommand(param) {
        console.log(param);
        if (isNullOrEmpty(param)) {
          return;
        }
        let siteId = param.data.siteInfo.id;
        if (siteId == "") {
          this.$message.error("非法操作");
          return;
        }
        switch (param.cmd) {
          case 0: //启动
            
            startWebSite(siteId);
            break;
          case 1: //停止            
            stopWebSite(siteId);
            break;
          case 2: //删除
            this.$confirm('是否确认删除该站点?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              deleteWebSite(siteId);
             
            });
            break;
          default:
            this.$message.error("非法操作");
            break;
        }
      },
    },
    emptyCheck(event) {
      var val = event.target.value;
      if (val == "") {
        this.$alert('该字段不能为空', '提示', {
          confirmButtonText: '确定',
          callback: action => {
            event.target.focus();
          }
        });
      } else {
        if (event.target.name == "siteName") {
          //检查名称是否被占用
          this.isSiteNameValid(val, event);
        }
      }
    },
    isSiteNameValid(name, et) {
      var event = et;
      this.$axios.get("/api/WebSiteInfo/CheckSiteName?id=" + this.sessionId + "&siteName=" + name)
        .then(res => {
          let ret = res.data;
          if (ret && ret.resultCode == 0) {
            if (ret.data.receiveData.resultCode != 0) {
              this.$alert('名称被占用', '提示', {
                confirmButtonText: '确定',
                callback: action => {
                  event.target.focus();
                }
              });
            }

          } else {
            this.$message.error(ret.resultMsg);
          }
        })
    },
    stopWebSite(siteId) {
      let url = "/api/WebSiteInfo/stop";
      this.$axios.post(url, {
        "siteId" : siteId
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '停止站点请求已发送，稍后刷新查看结果!'
        });
      }).catch((err) => {
        console.log(err);
      });
    },
    startWebSite(siteId) {
      let url = "/api/WebSiteInfo/start";
      this.$axios.post(url, {
        "siteId": siteId
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '启动站点请求已发送，稍后刷新查看结果!'
        });
      }).catch((err) => {
        console.log(err);
      });
    },
    deleteWebSite(siteId) {
      let url = "/api/WebSiteInfo/delete";
      this.$axios.post(url, {
        "siteId": siteId
      }).then((res) => {
        this.$message({
          type: 'success',
          message: '删除请求已发送，稍后刷新查看结果!'
        });
      }).catch((err) => {
        console.log(err);
      });
    },
    created() {
      console.log("created");
      this.requestId = this.$route.params.requestId;
      this.getData();

    },
    beforeUpdate() {
      //console.log("beforeUpdate");
    },
    computed: {
      clientName() {

      },

      isAddSite() {
        return this.dialogTitle == "创建站点";
      },
      siteVersionFile() {
        if (this.form.siteInfoExtend.webAssemblyFileName && this.form.siteInfoExtend.webAssemblyFileName != "") {
          return { "versionFileName": this.form.siteInfoExtend.webAssemblyFileName, "siteId": this.form.siteInfo.id, "siteName": this.form.siteInfo.siteName };
        } else {
          return {};
        }
      }
    },
    beforeRouteUpdate(to, from, next) {
      // react to route changes...
      // don't forget to call next()
      console.log("beforeRouteUpdate,");
      console.warn(to);
      this.requestId = this.$route.params.requestId;
      this.getData();
      next();
    }
  }
</script>
<style scoped>
  .numInputW {
    width: 200px;
  }

  .main {
    margin: 10px;
    padding: 10px;
  }

  .upload {
    width: 360px;
  }
</style>
